<template>
  <div class="wrapper">
    <BreakSpace label="主信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="infoMain" labelWidth="100" :list="formList" :formType="type" @formChange="changeHandle" :isSubmitBtn="false" />
    <!-- <infoProduct ref="infoProduct" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoProductChange"/> -->
    <div v-show="modelShow" >
      <BreakSpace label="车型选择" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <el-cascader
        v-model="seriesModelList"
        :options="modelOptions"
        :props="modelProps"
        :disabled="isOperator"
        style="width: 50%"
        size="medium"
        show-all-levels
        filterable
        :clearable="false"
      ></el-cascader>
    </div>
    <div v-show="dealerShow">
      <BreakSpace label="经销商选择" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <!-- table -->
      <FilterTable
        height="300"
        ref="dealerTable"
        :columns="dealerColumns"
        :dataSource="listDealer"
        :isSelectColumn="isSelectColumn"
        :datakey="'records'"
        :disabled="isOperator"
        :isToperInfo="false"
        :onColumnsChange="(dealerColumns) => (this.dealerColumns = dealerColumns)"
        columnsRef="notification_maintain_info_01"
      >
        <template slot="controls">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="dealerHeader" :disabled="isOperator">添加经销商</el-button>
          <!--<el-button size="small" type="primary" icon="el-icon-upload" @click="importFun()" :disabled="isOperator">经销商导入</el-button>-->
          <el-button size="small" type="primary" icon="el-icon-upload" @click="openimportDialog()" :disabled="isOperator">经销商导入</el-button>
        </template>
      </FilterTable>
      <BaseDialog
        style="min-height: 80vh"
        :visible.sync="visibleImport"
        width="80vw"
        title="模板导入"
        destroyOnClose
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
      >
        <ExcelImport ref="import" template-file-name="经销商导入模板.xlsx" :importRules="importRules" :onComplete="importComplete" @close="visibleImport = false" />
      </BaseDialog>
    </div>
    <div v-show="jobShow">

      <BreakSpace label="关键岗位选择" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <!-- table -->
      <FilterTable
        height="300"
        ref="dealerRoleTable"
        :columns="dealerRoleColumns"
        :dataSource="listDealerRole"
        :isSelectColumn="isSelectColumn"
        :datakey="'records'"
        :isToperInfo="false"
        :onColumnsChange="(dealerRoleColumns) => (this.dealerRoleColumns = dealerRoleColumns)"
        columnsRef="notification_maintain_info_02"
      >
        <template slot="controls">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="dealerRoleHeader" :disabled="isOperator">添加关键岗位</el-button>
        </template>
      </FilterTable>
    </div>
    <div v-show="carShow">
      <BreakSpace label="车厂用户角色" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <!-- table -->
      <FilterTable
        height="300"
        ref="oemRoleTable"
        :columns="oemRoleColumns"
        :dataSource="listOemRole"
        :isSelectColumn="isSelectColumn"
        :datakey="'records'"
        :disabled="isOperator"
        :isToperInfo="false"
        :onColumnsChange="(oemRoleColumns) => (this.oemRoleColumns = oemRoleColumns)"
        columnsRef="notification_maintain_info_03"
      >
        <template slot="controls">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="roleHeader" :disabled="isOperator">添加车厂角色</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="roleGroupHeader" :disabled="isOperator">添加角色分组</el-button>
        </template>
      </FilterTable>
    </div>
    <div>
      <BreakSpace label="附件" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <FormPanel ref="infoFile" :list="form" :cols="1" :formType="type" @formChange="changeHandleFile" :isSubmitBtn="false" :disabled="isOperator" />
    </div>
    <div>
      <BreakSpace label="主要内容" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <!--<Tinymce v-model="content" :height="300" style="padding-bottom:10px" actionUrl="/api/file/oss/upload" :disabled="isOperator" :wordsLimit="20000" :isUploadImage="isUploadImage" />-->
      <!--<TEXTAREA v-model="content" :height="300" style="padding-bottom:10px" :disabled="isOperator" :wordsLimit="200" ></TEXTAREA>-->
      <el-input v-model="content" :disabled="isOperator" type="textarea" :maxlength="5000" :autosize="{ minRows: 10, maxRows: 100 }" label="主要内容"></el-input>
    </div>

    <div>
      <BreakSpace label="操作节点" :containerStyle="{ marginBottom: '10px',marginTop: '10px' }" />
      <!-- table -->
      <FilterTable
        height="250"
        ref="logTable"
        :columns="logColumns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :isSelectColumn="isSelectColumn"
        :onColumnsChange="(logColumns) => (this.logColumns = logColumns)"
        columnsRef="notification_maintain_logTable_04"
      >
      </FilterTable>
    </div>

    <!-- 角色选择弹窗 -->
    <BaseDialog title="车厂角色选择" :visible.sync="visibleOemRole" width="1000px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <oem-role ref="addOemRole" @close="closeOemRole" />
    </BaseDialog>

    <!-- oem 角色分组选择弹窗 -->
    <BaseDialog title="车厂角色分组选择" :visible.sync="visibleOemRoleGroup" width="1000px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <oem-role-group ref="addOemRoleGroup" @close="closeOemRoleGroup" />
    </BaseDialog>

    <!-- dealer 角色分组选择弹窗 -->
    <BaseDialog
      title="经销商角色分组选择"
      :visible.sync="visibleDealerRoleGroup"
      width="1000px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <dealer-role-group ref="addDealerRoleGroup" @close="closeDealerRoleGroup" />
    </BaseDialog>

    <!-- 经销商选择弹窗 -->
    <BaseDialog title="经销商选择" :visible.sync="visibleDealer" width="1000px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <dealer-model ref="addDealer" selectType="multiple" v-model="initDealerData" @close="closeDealer" />
    </BaseDialog>

    <!-- 经销商角色类别选择弹窗 -->
    <BaseDialog title="关键岗位选择" :visible.sync="visibleDealerRole" width="1000px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <dealer-role ref="addDealer" v-model="initDealerRoleData" @close="closeRoleDealer" />
    </BaseDialog>

    <!-- 导入弹窗 -->
    <BaseDialog :visible.sync="isimportpop" destroyOnClose title="数据导入" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <importDealer menuId="-1" url="/api/cmscloud.channel/notification/import" @close="closeDealerImport" />
    </BaseDialog>

    <div class="dialogBottmView">
      <el-button @click="closeDialog()">取 消</el-button>
      <el-button @click="publishDialog" v-show="isPublish" type="primary" :disabled="isOperator" :loading="saveLoading">发 布</el-button>
      <el-button @click="publishDialog" v-show="isTiming" type="primary" :disabled="isOperator" :loading="saveLoading">定 时 发 布</el-button>
      <el-button @click="saveDialog" type="primary" :disabled="isOperator" :loading="saveLoading">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { authority } from '@/utils/authMixin';
import { dictionary } from '@/utils/dictMixin';
import {
  addNotification,
  getNotificationById,
  updateNotification,
  publishNotification,
  getUserInfo,
  getLogList,
  findFileByUrl,
  importConfirmSalesZone,
} from '@/api/cms-api/notification/maintain/index';
// import dealerModel from '@/pages/cms-common/dealerdata/indexWIthType';
import dealerModel from '@/pages/cms-common/dealerdata/indexWIthTypeNoPage';
import dealerRole from '@/pages/cms-pages/notification/maintain/dealerRole';
import oemRole from '@/pages/cms-pages/notification/maintain/oemRole';
import oemRoleGroup from '@/pages/cms-pages/notification/maintain/oemRoleGroup';
import dealerRoleGroup from '@/pages/cms-pages/notification/maintain/dealerRoleGroup';
import importDealer from '@/pages/cms-common/import/dealerImport';
import { findFinanceCompany } from '@/api/cms-api/origin/originInfo/OEM';
import { getAppId } from '@/assets/js/auth';
import SERVER from '@/api/server';
import { formatdateByTime, formatdate } from '@/utils/index';
import infoProduct from './infoProduct'; //授权车型
import { isArray } from 'util';
import config from '@/assets/js/config';
import ExcelImport from '@/components/ExcelImport';
import moment from 'moment';
import { afterCurrentTime } from '@/utils/validate.js';
import { getSeriesModelTree } from '@/api/cms-common/basedata';

export default {
  mixins: [authority, dictionary],
  components: {
    dealerModel,
    dealerRole,
    oemRole,
    importDealer,
    oemRoleGroup,
    dealerRoleGroup,
    infoProduct,
    ExcelImport,
  },
  props: {
    value: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      formList: this.createFormList(),
      form: this.createForm(),
      type: this.value.type,
      notificationId: this.value.type != 'add' ? this.value.notificationId : null,
      oemRoleColumns: this.value.type === 'show' ? this.creatHeader4OemRoleColumns4disabled() : this.creatHeader4OemRoleColumns(),
      listOemRole: [],
      dealerColumns: this.value.type === 'show' ? this.creatHeader4DealerColumns4disabled() : this.creatHeader4DealerColumns(),
      listDealer: [],
      dealerRoleColumns: this.value.type === 'show' ? this.creatHeader4DealerRoleColumns4disabled() : this.creatHeader4DealerRoleColumns(),
      listDealerRole: [],
      isTiming: false,
      isPublish: true,
      isSelectColumn: false,
      isUploadImage: false,
      visibleOemRole: false,
      visibleOemRoleGroup: false,
      visibleDealerRoleGroup: false,
      visibleDealer: false,
      visibleDealerRole: false,
      visibleImport: false,

      initDealerData: {},
      initDealerRoleData: {},
      initOemRoleData: {},
      content: '',
      dataMain: null, // 第一个表单的数据
      dataInfo: null,
      caseUrlList: [],
      caseUrl: [],
      publishType: '',

      isShow: false, //经销商弹框选择是否选择

      jobShow:true,
      carShow:true,
      dealerShow: false,
      modelShow: false,
      dealerTypeShow: false,
      isOperator: this.value.type === 'show' ? true : false, // 是否是详情
      userInfoData: null,
      saveLoading: false,
      isimportpop: false, //导入弹窗默认关闭
      allIssuedType: '',
      logColumns: this.creatLogHeader(),
      fetchApi: getLogList,
      fetchParams: { notificationId: this.value.type != 'add' ? this.value.notificationId : null },
      formData: {},
      importRules: [{ prop: 'dealerCode', title: '经销商代码', rule: { required: true, message: '经销商代码不能为空' } }],
      seriesModelList: [],
      modelProps: { multiple: true },
      modelOptions: [],
      dealerTypeRules: [{ required: true, message: '请选择发布类型', trigger: 'blur' }],
      dealerTypeArrayAll:[
        { value: 1, text: '指定经销商' },
        { value: 2, text: '授权车型' },
      ],
      dealerTypeArrayModel:[
        { value: 2, text: '授权车型' },
      ],
    };
  },
  created() {
    this.initUserInfoData();
  },
  // 页面加载完成 请求接口
  mounted() {
    if (this.notificationId != null) {
      this.initData();
      // this.init();
    }
    this.getModels();
  },

  methods: {
    async getModels() {
      let res = await getSeriesModelTree();
      if (res.resultCode == 200) {
        this.modelOptions = res.data;
      }
    },
    // async init() {
    //   try {
    //     let res = await getDetails(this.value.id, {});
    //     if (res.resultCode === 200) {
    //       //转换附件为list<Sting>
    //       this.formData = this.transformAllEnclosureString(res.data);
    //       this.formData.inputNumber = '';
    //       this.formData.inputChar = '';
    //       this.$nextTick(() => {
    //         this.$refs.infoProduct.init();
    //       });
    //     }
    //   } catch (e) {
    //     console.log("页面初始化异常:", e);
    //   } finally {
    //     this.closeLoding(this.loadingVm);
    //   }

    // },

    /**
     * 获取待提交数据
     * @returns {*|{}}
     */
    getSavingData() {
      //取数据
      let allData = { ...this.formData };
      // allData.shopBusinessType = types.SHOP_BUSINESS_SALES;

      // tongzhitonggaoxinxi
      this.$refs.infoMain.excuteFormData(this.$refs.infoMain.form);
      allData = Object.assign(allData, this.$refs.infoMain.form);

      //授权车型
      // this.$refs.infoProduct.$refs.FormPanel.excuteFormData(this.$refs.infoProduct.$refs.FormPanel.form);
      // allData = Object.assign(allData, this.$refs.infoProduct.$refs.FormPanel.form);

      allData.seriesModelList = this.seriesModelList;
      return allData;
    },
    // saveDialog() {
    //   // this.loadingVm = this.openLoding('.cover-container');
    //   let allData = this.getSavingData();

    //   this.submit(allData);
    // },
    infoProductChange(data) {
      // console.log(3)
      this.$refs.infoProduct.saveDialog();
    },
    //转化表单的附件 转换为list<Map<String,Object>>（提交前使用）
    //不再使用由IMG转FILE
    transformAllEnclosure(data) {
      let rdata = Object.assign({}, data);

      rdata.designFeeEnclosureList = this.transformEnclosureList(rdata.designFeeEnclosureList); //设计费附件
      rdata.cashDepositEnclosureList = this.transformEnclosureList(rdata.cashDepositEnclosureList); //保证金附件

      rdata.businessLicenseEnclosureList = this.transformEnclosureList(rdata.businessLicenseEnclosureList); //营业执照扫描件
      rdata.legalRepresentativeEnclosureList = this.transformEnclosureList(rdata.legalRepresentativeEnclosureList); //法定代表人附件
      rdata.firstPaymentEnclosureList = this.transformEnclosureList(rdata.firstPaymentEnclosureList); //首笔提车款附件

      rdata.openAccountProveEnclosureList = this.transformEnclosureList(rdata.openAccountProveEnclosureList); //开户证明附件

      rdata.licenceEnclosureList = this.transformEnclosureList(rdata.licenceEnclosureList); //许可证附件
      return rdata;
    },
    //转化表单的附件 转换为list<Sting>（回显使用）
    transformAllEnclosureString(data) {
      let rdata = data;

      rdata.designFeeEnclosureList = this.transformEnclosureStringList(rdata.designFeeEnclosureList); //设计费附件
      rdata.cashDepositEnclosureList = this.transformEnclosureStringList(rdata.cashDepositEnclosureList); //保证金附件

      rdata.businessLicenseEnclosureList = this.transformEnclosureStringList(rdata.businessLicenseEnclosureList); //营业执照扫描件
      rdata.legalRepresentativeEnclosureList = this.transformEnclosureStringList(rdata.legalRepresentativeEnclosureList); //法定代表人附件
      rdata.firstPaymentEnclosureList = this.transformEnclosureStringList(rdata.firstPaymentEnclosureList); //首笔提车款附件

      rdata.openAccountProveEnclosureList = this.transformEnclosureStringList(rdata.openAccountProveEnclosureList); //开户证明附件

      rdata.licenceEnclosureList = this.transformEnclosureStringList(rdata.licenceEnclosureList); //许可证附件

      //经销商形式
      let dealerAttachAuthList = [];
      if (isArray(rdata.dealerAttachAuthDetailList)) {
        rdata.dealerAttachAuthDetailList.forEach((x) => {
          dealerAttachAuthList.push(x.financeCompanyId);
        });
      }
      rdata.dealerAttachAuthDetailList = [];
      rdata.dealerAttachAuthList = dealerAttachAuthList;

      //车系
      let dealerAttachSeriesList = [];
      if (isArray(rdata.dealerAttachSeriesDetailList)) {
        rdata.dealerAttachSeriesDetailList.forEach((x) => {
          dealerAttachSeriesList.push(x.seriesId);
        });
      }
      rdata.dealerAttachSeriesList = dealerAttachSeriesList;
      rdata.dealerAttachSeriesDetailList = [];
      //车型
      let dealerAttachModelList = [];
      if (isArray(rdata.dealerAttachModelDetailList)) {
        rdata.dealerAttachModelDetailList.forEach((x) => {
          dealerAttachModelList.push(x.modelId);
        });
      }
      rdata.dealerAttachModelList = dealerAttachModelList;
      rdata.dealerAttachModelDetailList = [];
      console.log('rdata------', rdata);
      return rdata;
    },
    //转换成附件对象 转换为list<Map<String,Object>>
    transformEnclosureList(list) {
      let fileUrlList = [];
      if (!isArray(list)) {
        return fileUrlList;
      }
      //不再使用由IMG转FILE
      // for (let i = 0; i < list.length; i++) {
      // 	let fileUrl = list[i];
      // 	fileUrl = fileUrl.replace(/\\/g,"/");
      // 	fileUrlList.push(Object.assign({},{"name":fileUrl.substring(fileUrl.lastIndexOf('/')+1)},{"url":fileUrl}));
      // }
      // return fileUrlList;
      return list;
    },
    //转换成附件对象(回显) 转换为list<Sting>
    transformEnclosureStringList(list) {
      let fileUrlList = [];
      if (!isArray(list)) {
        return fileUrlList;
      }
      //不再使用由IMG转FILE
      // for (let i = 0; i < list.length; i++) {
      // 	let fileUrl = list[i];
      // 	fileUrlList.push(fileUrl.fileId);
      // }
      list.forEach((x) => {
        fileUrlList.push({ name: x.fileName, url: x.fileId });
      });
      return fileUrlList;
    },
    //日志table表头和数据源
    creatLogHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        { title: '节点操作描述', dataIndex: 'operateDes', sorter: true },
        { title: '节点操作人', dataIndex: 'operatePersonName', sorter: true },
        {
          title: '节点操作时间',
          dataIndex: 'operateTime',
          sorter: true,
          render: (props) => {
            return <span>{formatdateByTime(props.row.operateTime)} </span>;
          },
        },
      ];
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '类别',
          fieldName: 'notificationType',
          placeholder: '请选择',
          initialValue: 15611001,
          clearable: false,
          itemList: this.createDictList('1561'),
          rules: [{ required: true, message: '请选择类别', trigger: 'blur' }],
        },
        {
          type: 'TEXT_AREA',
          label: '主题',
          fieldName: 'notificationTitle',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            { required: true, message: '必填', trigger: 'blur' },
            { max: 200, message: '长度最大200字符', trigger: 'blur' },
          ],
        },
        {
          type: 'INPUT',
          label: '发布部门',
          disabled: true,
          fieldName: 'publishOrgName',
          initialValue: '',
          rules: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        },
        {
          type: 'SELECT',
          label: '紧急程度',
          fieldName: 'urgency',
          placeholder: '请选择',
          initialValue: 15621001,
          clearable: false,
          itemList: this.createDictList('1562'),
          rules: [{ required: true, message: '请选择紧急程度', trigger: 'blur' }],
        },
        {
          type: 'SELECT',
          label: '长期通知',
          fieldName: 'isLong',
          change: this.isLongChange,
          placeholder: '请选择',
          initialValue: 10041001,
          clearable: false,
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '请选择是否长期通知', trigger: 'blur' }],
        },
        {
          type: 'DATE',
          label: '有效期至',
          fieldName: 'endTime',
          placeholder: '请选择',
          valueFormat: 'yyyy-MM-dd',
          initialValue: '',
          minDateTime: moment().add(-1, 'days'),
          hidden: true,
          rules: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        },
        {
          type: 'SELECT',
          label: '定时发布',
          fieldName: 'isTiming',
          placeholder: '请选择',
          initialValue: 10041002,
          itemList: this.createDictList('1004'),
          change: this.isTimingChange,
          clearable: false,
          rules: [{ required: true, message: '请选择是否定时发布', trigger: 'change' }],
        },
        {
          type: 'DATE',
          dateType: 'datetime',
          format: 'yyyy-MM-dd HH:00',
          label: '定时发布时间',
          fieldName: 'timing',
          placeholder: '请选择',
          popperClassName: 'poppertiming',
          hidden: true,
          initialValue: '',
          minDateTime: moment().add(-1, 'days'),
          rules: [
            { required: true, message: '请选择发布时间', trigger: 'blur' },
            { validator: afterCurrentTime, trigger: 'blur' },
          ],
        },
        {
          type: 'SELECT',
          label: '全网发布',
          fieldName: 'isAll',
          placeholder: '请选择',
          initialValue: 10041001,
          itemList: this.createDictList('1004'),
          change: this.isAllChange,
          hidden: false,
          clearable: false,
          rules: [{ required: true, message: '请选择发布范围', trigger: 'blur' }],
        },
        {
          type: 'SELECT',
          label: '发布类型',
          fieldName: 'dealerType',
          placeholder: '请选择',
          initialValue: null,
          disabled: false,
          itemList: [
            { value: 2, text: '授权车型' },
          ],
          hidden: false,
          change: this.dealerTypeChange,
          rules: [],
        },
      ];
    },
    createForm() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'caseUrl',
          initialValue: [],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`, // 上传的地址
            multiple: true,
            limit: 5,
            fileTypes: ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'rar', 'zip', 'txt', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx','mp4','mov'],
            fileSize: 70,
            max: 1024 * 200,
            // extra:{
            //   // fileSize: 70,
            //   fileTypes: ['mp4','mov']
            // }
          },
        },
      ];
    },
    // 车厂角色选择列表
    creatHeader4OemRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteoemRole(props.$index)}>
                  删除
                </el-button>
              </div>
            );
          },
        },
        { title: '角色代码', dataIndex: 'roleCode', sorter: true },
        { title: '角色名称', dataIndex: 'roleName', sorter: true },
      ];
    },
    //经销商列表
    creatHeader4DealerColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteDealer(props.$index)}>
                  删除
                </el-button>
              </div>
            );
          },
        },
        // { title: '区域', dataIndex: 'deptName', sorter: true },
        { title: '渠道代码', dataIndex: 'dealerCode', sorter: true },
        { title: '渠道名称', dataIndex: 'dealerShortname', sorter: true },
      ];
    },
    //经销商角色类别列表
    creatHeader4DealerRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteDealerRole(props.$index)}>
                  删除
                </el-button>
              </div>
            );
          },
        },
        { title: '角色名称', dataIndex: 'text', sorter: true },
      ];
    },
    // 车厂角色选择列表
    creatHeader4OemRoleColumns4disabled() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        { title: '角色代码', dataIndex: 'roleCode', sorter: true },
        { title: '角色名称', dataIndex: 'roleName', sorter: true },
      ];
    },
    //经销商列表
    creatHeader4DealerColumns4disabled() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        { title: '区域', dataIndex: 'deptName', sorter: true },
        { title: '公司代码', dataIndex: 'dealerCode', sorter: true },
        { title: '公司名称', dataIndex: 'dealerShortname', sorter: true },
      ];
    },
    //经销商角色类别列表
    creatHeader4DealerRoleColumns4disabled() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.$index + 1}</span>;
          },
        },
        { title: '角色名称', dataIndex: 'text', sorter: true },
      ];
    },
    // 角色选择窗口打开 -传数据
    roleHeader() {
      this.initDealerRoleData = {
        id: 1001,
      }; //行id
      this.visibleOemRole = true;
    },
    // 角色选择窗口 -返回数据
    closeOemRole(data) {
      // this.listOemRole = data.data;
      this.addSelectOemRole(data.data);
      this.visibleOemRole = data.visible; //关闭弹窗
    },

    // oem 分组角色选择窗口 -打开
    roleGroupHeader() {
      this.visibleOemRoleGroup = true;
    },
    //oem 分组角色选择窗口 -关闭
    closeOemRoleGroup(data) {
      this.addSelectOemRole(data.data);
      this.visibleOemRoleGroup = false; //关闭弹窗
    },

    //dealer 分组角色选择窗口 -打开
    dealerRoleGroupHeader() {
      this.visibleDealerRoleGroup = true;
    },
    //dealer 分组角色选择窗口 -关闭
    closeDealerRoleGroup(data) {
      this.addSelectRoleDealer(data.data);
      this.visibleDealerRoleGroup = false; //关闭弹窗
    },

    // 经销商选择窗口 -传数据
    dealerHeader() {
      this.initDealerData = {
        excludeBigCustomer: true, // 是否查询大客户经销商，如果查询  false，不查询 true
        id: 1001,
        orgTypes: this.userInfoData.orgType,
      }; //行id
      if (getAppId() == 'beijing') {
        this.initDealerData.orgIdS = this.userInfoData.orgId;
      }
      this.visibleDealer = true;
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      // this.listDealer = data.data;
      this.addSelectDealer(data.data);
      this.visibleDealer = data.visible; //关闭弹窗
    },
    closeDealerImport(data) {
      this.addSelectDealer(data.data);

      this.isimportpop = false;
    },

    // 3 经销商类别选择窗口 -传数据
    dealerRoleHeader() {
      this.initDealerRoleData = {
        orgTypes: this.userInfoData.orgType,
        id: 1001,
      }; //行id
      this.visibleDealerRole = true;
    },
    // 3 经销商角色类别关闭窗口 -返回数据
    closeRoleDealer(data) {
      //this.listDealerRole = data.data;
      this.addSelectRoleDealer(data.data);
      this.visibleDealerRole = data.visible; //关闭弹窗
    },
    //判断经销商是否已经在列表中选择
    isExistInDatasouce(dealerCode) {
      let r = false;
      if (this.listDealer && this.listDealer.length > 0) {
        for (let dIdx = 0; dIdx < this.listDealer.length; dIdx++) {
          let tcode = this.listDealer[dIdx].dealerCode;
          if (tcode === dealerCode) {
            r = true;
            break;
          }
        }
      }
      return r;
    },
    isExistInlistOemRole(roleCode) {
      let r = false;
      if (this.listOemRole && this.listOemRole.length > 0) {
        for (let dIdx = 0; dIdx < this.listOemRole.length; dIdx++) {
          let tcode = this.listOemRole[dIdx].roleCode;
          if (tcode === roleCode) {
            r = true;
            break;
          }
        }
      }
      return r;
    },
    isExistInlistRoleDealer(value) {
      let r = false;
      if (this.listDealerRole && this.listDealerRole.length > 0) {
        for (let dIdx = 0; dIdx < this.listDealerRole.length; dIdx++) {
          let tcode = this.listDealerRole[dIdx].value;
          if (tcode === value) {
            r = true;
            break;
          }
        }
      }
      return r;
    },

    //添加选择经销商到列表中
    addSelectDealer(dealers) {
      if (dealers != null && typeof dealers != 'undefined' && dealers.length > 0)
        dealers.forEach((dealer) => {
          let dealerCode = dealer.dealerCode;
          if (!this.isExistInDatasouce(dealerCode)) {
            // let dealerNode = {
            //   dealerShortname: dealer.dealerShortname,
            //   dealerCode: dealer.dealerCode,
            //   deptName: dealer.deptName,
            //   deptId: dealer.deptId
            // };
            this.listDealer.push(dealer);
          }
        });
      this.listDealer.dataMark = false;
    },
    //添加选择车角色到列表中
    addSelectOemRole(oemRoles) {
      if (oemRoles != null && typeof oemRoles != 'undefined' && oemRoles.length > 0) {
        oemRoles.forEach((oemRole) => {
          let roleCode = oemRole.roleCode;
          if (!this.isExistInlistOemRole(roleCode)) {
            this.listOemRole.push(oemRole);
          }
        });
        this.listOemRole.dataMark = false;
      }
    },
    //添加选择经销商角色到列表中
    addSelectRoleDealer(dealerRoles) {
      if (dealerRoles != null && typeof dealerRoles != 'undefined' && dealerRoles.length > 0) {
        dealerRoles.forEach((dealerRole) => {
          let value = dealerRole.value;
          if (!this.isExistInlistRoleDealer(value)) {
            this.listDealerRole.push(dealerRole);
          }
        });
        this.listDealerRole.dataMark = false;
      }
    },
    //发布
    async publishDialog() {
      this.publishType = 'publish';
      this.$refs.infoMain.SUBMIT_FORM();
    },
    //保存
    async saveDialog() {
      this.publishType = this.value.type;
      this.$refs.infoMain.SUBMIT_FORM();
    },
    changeHandle(data) {
      this.dataMain = data;
      this.$refs.infoFile.SUBMIT_FORM();
    },
    importFun() {
      this.isimportpop = true;
    },
    changeHandleFile(data) {
      console.log('change file');
      this.caseUrlList = [];
      for (let i = 0; i < data.caseUrl.length; i++) {
        let temp = {};

        temp.url = data.caseUrl[i].url;
        temp.name = data.caseUrl[i].name;

        this.caseUrlList.push(temp);
      }
      this.dataInfo = this.caseUrlList;

      if (this.publishType === 'add') {
        this.submit();
      } else if (this.publishType === 'publish') {
        this.publish();
      } else if (this.publishType === 'edit') {
        this.update();
      }
    },
    // 关闭当前页面操作
    closeDialog(type) {
      this.$emit('close', { visible: false, type: type });
    },
    deleteDealer(index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.listDealer.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!',
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    deleteDealerRole(index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.listDealerRole.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!',
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    deleteoemRole(index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.listOemRole.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!',
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 发布
    async publish() {
      var flag = this.packageData();
      if (flag === -1) {
        return;
      }
      if (this.dataMain.isAll === 10041001) {
        //关键岗位
        if (this.dataMain.listDealerRole.length == 0) {
          this.$notify.warning({ title: '提示信息', message: '请添加经销商岗位信息！' });
          return -1;
        }
        //授权车型
        if(this.dataMain.dealerType === 2){
          if (this.seriesModelList.length == 0) {
            this.$notify.warning({ title: '提示信息', message: '请添加授权车型信息！' });
            return -1;
          }
        }
      } else {
        if (this.dataMain.dealerType == 1) {
          if (this.dataMain.listDealer.length == 0 ) {
            this.$notify.warning({ title: '提示信息', message: '请添加经销商信息！' });
            return -1;
          }else if (this.dataMain.listDealerRole.length == 0) {
            this.$notify.warning({ title: '提示信息', message: '请添加经销商岗位信息！' });
            return -1;
          }
        }
      }

      if (this.type === 'add') {
        this.saveLoading = true;
        this.validReturnDate(await publishNotification(this.dataMain, -1));
      } else if (this.type === 'edit') {
        this.saveLoading = true;
        this.validReturnDate(await publishNotification(this.dataMain, this.notificationId));
      }
    },
    // 更新
    async update() {
      var flag = this.packageData();
      if (flag === -1) {
        return;
      }
      this.saveLoading = true;
      this.validReturnDate(await updateNotification(this.dataMain, this.notificationId));
    },
    // 保存
    async submit() {
      var flag = this.packageData();
      if (flag === -1) {
        return;
      }

      this.saveLoading = true;
      this.validReturnDate(await addNotification(this.dataMain));
    },
    validReturnDate(res) {
      if (res.resultCode === 200) {
        this.saveLoading = false;
        this.$notify.success({ title: '提示信息', message: '操作成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '操作失败!' });
      }
    },
    transTiming(value) {
      console.log('timing orgin value:', value);
      let regex = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3]):([0-5][0-9])$/;
      let regex2 = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/;
      let regex3 = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3])$/;
      if (regex.test(value)) {
        value = value + ':00';
      } else if (regex2.test(value)) {
        value = value;
      } else if (regex3.test(value)) {
        value = value + ':00:00';
      } else {
        value = value;
      }
      return value;
    },

    // 数据组装
    packageData() {
      let allData = this.getSavingData();
      this.dataMain.notificationContent = this.content;
      this.dataMain.url = this.dataInfo;
      this.dataMain.allIssuedType = this.allIssuedType;
      //定时时间转换
      this.dataMain.timing = this.transTiming(this.dataMain.timing);
      this.packageUserInfoData();
      this.packageListDealer();
      this.packageListDealerRole();
      this.packageListOemRole();
      this.dataMain = { ...allData, ...this.dataMain };
      console.log(this.dataMain);
      if (this.dataMain.isAll === 10041001) {
        // 是全网发布 清空经销商数据
        this.dataMain.listDealer = [];
      }

      // if (this.dataMain.notificationContent.length > 4000) {
      //   this.$notify.error({ title: '提示信息', message: '文本过长' });
      //   return -1;
      // }
    },
    // 封装用户信息
    packageUserInfoData() {
      // if(this.type === "add"){
      this.dataMain.publishOrgId = this.userInfoData.orgId;
      this.dataMain.publishPerson = this.userInfoData.userId;
      this.dataMain.publishPersonName = this.userInfoData.userName;
      // }
    },
    // 封装经销商信息
    packageListDealer() {
      var temp = [];
      for (var i = 0; i < this.listDealer.length; i++) {
        var body = {};
        body.dealerName = this.listDealer[i].dealerShortname;
        body.ownerCode = this.listDealer[i].dealerCode;
        body.dealerCompanyId = this.listDealer[i].dealerCompanyId;
        body.dealerCompanyCode = this.listDealer[i].dealerCompanyCode;
        temp.push(body);
      }
      this.dataMain.listDealer = temp;
    },
    // 封装经销商角色类别信息
    packageListDealerRole() {
      var temp = [];
      for (var i = 0; i < this.listDealerRole.length; i++) {
        var body = {};
        body.codeCnDesc = this.listDealerRole[i].text;
        body.codeId = this.listDealerRole[i].value;
        temp.push(body);
      }
      this.dataMain.listDealerRole = temp;
    },
    // 封装车厂角色信息
    packageListOemRole() {
      if (this.listOemRole == null) {
        this.dataMain.listOemRole = [];
        return;
      }
      var temp = [];
      for (var i = 0; i < this.listOemRole.length; i++) {
        var body = {};
        body.roleCode = this.listOemRole[i].roleCode;
        body.roleId = this.listOemRole[i].roleId;
        body.roleName = this.listOemRole[i].roleName;
        temp.push(body);
      }
      this.dataMain.listOemRole = temp;
    },
    // 通过ID获取页面详情数据
    async initData() {
      this.saveLoading = true;
      if (this.value.type == 'edit') {
        var res = await getNotificationById(this.notificationId, 'editFile');
      } else {
        var res = await getNotificationById(this.notificationId);
      }

      if (res.resultCode === 200) {
        this.saveLoading = false;
        await this.initPackageData(res);
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '获取数据异常，请稍后再试！' });
        this.closeDialog();
      }
    },
    // 获取用户信息
    async initUserInfoData() {
      this.saveLoading = true;
      var res = await getUserInfo();
      if (res.resultCode === 200) {
        this.saveLoading = false;
        this.formList[2].initialValue = res.data.orgName;
        this.userInfoData = res.data;
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '获取数据异常，请稍后再试！' });
        this.closeDialog();
      }
    },
    // 初始化数据封装
    async initPackageData(res) {
      console.log('res----', res);
      this.dataMain = res.data;
      //赋值
      this.formList.forEach((x) => {
        x.initialValue = this.dataMain[x.fieldName];

        if (x.fieldName == 'isLong' && '10041002' == this.dataMain[x.fieldName]) {
          this.formList.find((item) => item.fieldName === 'endTime').hidden = false;
        }
        if (x.fieldName == 'timing' && null != this.dataMain[x.fieldName]) {
          this.formList.find((item) => item.fieldName === 'timing').hidden = false;
          //this.formList[7].hidden = false;
          this.isTiming = true;
          this.isPublish = false;
        }
      });

      // this.initForm.find(item => item.fieldName === 'dealerAttachAuthList').initialValue = this.pdata.dealerAttachAuthDetailList;
      // this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').initialValue = this.pdata.dealerAttachSeriesDetailList;
      // this.initForm.find(item => item.fieldName === 'dealerAttachModelList').initialValue = this.pdata.dealerAttachModelDetailList;

      this.formData = this.transformAllEnclosureString(res.data);
      this.formData.inputNumber = '';
      this.formData.inputChar = '';
      this.$nextTick(() => {
        this.$refs.infoProduct.init();
      });

      let arr = [];
      if (res.data.allIssuedType.indexOf(',') == -1) {
        arr.push(Number(res.data.allIssuedType));
      } else {
        res.data.allIssuedType.split(',').forEach((x) => {
          arr.push(Number(x));
        });
      }

      // this.formList.find(item => item.fieldName === 'allIssuedTypeIds').initialValue = arr;
      this.allIssuedType = res.data.allIssuedType;
      this.isAllChange(res.data.isAll);
      this.dealerTypeChange(res.data.dealerType);
      this.content = res.data.notificationContent;

      this.listOemRole = res.data.listOemRole; // TODO 厂端角色获取

      //车型列表
      this.seriesModelList = res.data.seriesModelList;
      await this.initUrl(res.data.url); // TODO 附件回显
      this.initPackageDealerData(res.data.listDealer); //回显经销商数据
      this.initPackageDealerRoleData(res.data.listDealerRole); //回显经销商角色类别数
    },
    initPackageDealerData(data) {
      let arr = [];
      for (var i = 0; i < data.length; i++) {
        var body = {};
        body.dealerShortname = data[i].dealerName;
        body.dealerCode = data[i].ownerCode;
        body.deptName = data[i].deptName;
        body.dealerCompanyId = data[i].dealerCompanyId;
        body.dealerCompanyCode = data[i].dealerCompanyCode;
        arr.push(body);
      }
      this.listDealer = arr;
    },
    initPackageDealerRoleData(data) {
      let arr = [];
      for (var i = 0; i < data.length; i++) {
        var body = {};
        body.text = data[i].codeCnDesc;
        body.value = data[i].codeId;
        arr.push(body);
      }
      console.log('listDealerRole---', arr);
      this.listDealerRole = arr;
    },
    async initUrl(data) {
      //明细查看时地址做转换
      // if(this.value.type === 'show'){
      //   for(let i = 0; i < data.length; i++){
      //     let t = data[i];
      //     await findFileByUrl(t.url).then(res => {
      //       t.url = res.data;
      //     });
      //   }
      // }

      console.log('before url set:', data);
      // 附件回显
      this.form.find((x) => x.fieldName === 'caseUrl').initialValue = data;
      console.log('after url set:', data);
    },
    isLongChange(val) {
      if (val === 10041002) {
        this.formList.find((item) => item.fieldName === 'endTime').hidden = false;
        this.formList.find((item) => item.fieldName === 'isLong').initialValue = 10041002;
      } else {
        this.formList.find((item) => item.fieldName === 'endTime').hidden = true;
        this.formList.find((item) => item.fieldName === 'isLong').initialValue = 10041001;
      }
    },
    isAllChange(val) {
      let dealerType = null;
      if (val === 10041001) {
        if(this.value.type == 'add'){
          this.formList.find((item) => item.fieldName === 'dealerType').initialValue = null;
        }
        this.formList.find((item) => item.fieldName === 'dealerType').hidden = false;
        this.formList.find((item) => item.fieldName === 'dealerType').itemList = this.dealerTypeArrayModel;
        this.formList.find((item) => item.fieldName === 'dealerType').disabled = this.value.type == 'show' ? true : false;
        this.formList.find((item) => item.fieldName === 'dealerType').rules = [];
        this.dealerTypeChange(this.formList.find((item) => item.fieldName === 'dealerType').initialValue);
      } else {
        this.formList.find((item) => item.fieldName === 'dealerType').initialValue = 1;
        this.formList.find((item) => item.fieldName === 'dealerType').hidden = false;
        this.formList.find((item) => item.fieldName === 'dealerType').itemList = this.dealerTypeArrayAll;
        this.formList.find((item) => item.fieldName === 'dealerType').disabled = true;
        this.formList.find((item) => item.fieldName === 'dealerType').rules = this.dealerTypeRules;
        this.dealerTypeChange(this.formList.find((item) => item.fieldName === 'dealerType').initialValue);
      }
    },
    dealerTypeChange(val) {
      if (val == 1) {
        this.dealerShow = true;
        this.modelShow = false;
        this.seriesModelList = [];
      } else if (val == 2) {
        this.dealerShow = false;
        this.modelShow = true;
        this.listDealer = [];
      }else{
        this.dealerShow = false;
        this.modelShow = false;
        this.seriesModelList = [];
        this.listDealer = [];
      }
    },
    isTimingChange(val) {
      if (val === 10041001) {
        this.formList.find((item) => item.fieldName === 'timing').hidden = false;
        this.formList.find((item) => item.fieldName === 'isTiming').initialValue = 10041001;
        this.isTiming = true;
        this.isPublish = false;
      } else {
        this.formList.find((item) => item.fieldName === 'timing').hidden = true;
        this.formList.find((item) => item.fieldName === 'isTiming').initialValue = 10041002;
        this.isTiming = false;
        this.isPublish = true;
      }
    },
    async createAuthList(params) {
      let res = await findFinanceCompany(params);

      if (res.resultCode === 200) {
        this.formList.find((item) => item.fieldName === 'allIssuedTypeIds').itemList = [];
        res.data.forEach((x) => {
          this.formList.find((item) => item.fieldName === 'allIssuedTypeIds').itemList.push({ text: x.financeCompanyName, value: x.financeCompanyId });
        });
      }
    },
    async authChange(val) {
      this.allIssuedType = val.join(',');
    },

    openimportDialog() {
      this.visibleImport = true;
    },
    async importComplete(datas, callback) {
      importConfirmSalesZone(datas).then((res) => {
        if (res) {
          if (res.success) {
            this.visibleImport = false;
            this.$notify.success({ title: '提示信息', message: '批量导入成功' });
            this.addSelectDealer(res.data);
            callback();
            this.drawerClose('refresh');
          } else {
            callback(res.data);
          }
        } else {
          callback([{ errormsg: '服务器运行异常' }]);
        }
      });
    },
  },
};
</script>
<style>
.poppertiming .el-scrollbar:nth-of-type(1) {
  width: 100% !important;
}
.poppertiming .el-scrollbar:nth-of-type(2) {
  display: none !important;
}
.el-cascader-panel .el-scrollbar {
  max-height: 300px;
}
</style>

<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
